#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SLInit(SL* ps)
{
	assert(ps);

	ps->a = (DataType*)malloc(4 * sizeof(DataType));
	if (ps->a == NULL)
	{
		perror("malloc failed");
		exit(-1);
	}
	ps->size = 0;
	ps->capacity = 4;
}

void SLDestroy(SL* ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

void SLPrint(SL* ps)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}
int SLFind(SL* ps, DataType x)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->size; ++i)
	{
		if (ps->a[i] == x)
			return i;
	}
	return -1;
}
static void Check_capacity(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		DataType* ptr = (DataType*)realloc(ps->a, ps->capacity * 2 * sizeof(DataType));
		if (ptr == NULL)
		{
			perror("realloc failed");
			exit(-1);
		}

		ps->a = ptr;
		ps->capacity *= 2;
	}
}

void SLPushBack(SL* ps, DataType x)
{
	assert(ps);
	Check_capacity(ps);
	ps->a[ps->size] = x;
	ps->size++;
}

void SLPopBack(SL* ps)
{
	assert(ps->size > 0);
	ps->size--;
}

void SLPushFront(SL* ps, DataType x)
{
	Check_capacity(ps);
	for (int i = ps->size; i>0; i--)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[0] = x;
	ps->size++;
}

void SLPopFront(SL* ps)
{
	assert(ps->size > 0);
	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}

void SLInsert(SL* ps, int pos, int x)
{
	assert(pos >= 0 && pos <= ps->size);
	Check_capacity(ps);
	int i = 0;
	for (i = ps->size; i > pos; i--)
	{
		ps->a[i] = ps->a[i - 1];
	}
	ps->a[pos] = x;
	ps->size++;
}

void SLErase(SL* ps, int pos)
{
	assert(pos >= 0 && pos < ps->size);
	int i = 0;
	for (i = pos; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}